class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
}

/**
 * 230. 二叉搜索树中第 K 小的元素
 * https://leetcode.cn/problems/kth-smallest-element-in-a-bst/description/
 */
class Solution {
    int ret = 0, count = 0;
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        dfs(root);
        return ret;
    }

    public void dfs(TreeNode root) {
        if(root == null || count == 0) return;

        dfs(root.left);

        count--;
        if(count == 0) {
            ret = root.val;
            return;
        }
        
        dfs(root.right);

    }
}